package com.example.administrator.newxlmedical;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.example.administrator.baseproject.BaseActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import adapters.LogDetailAdapter;
import beans.GoodsDetailInfoBean;
import beans.LogBean;
import beans.LogDetailBean;
import beans.OperateLogDetailsBean;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import constants.Constants;
import constants.HandlerConstant;
import dialogs.GoodsDetialsDialog;
import interfaces.MyItemClickListener;
import netframe.GetRetrofit;
import netframe.MyAction1;
import netframe.NetAddress;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.observables.GroupedObservable;
import rx.schedulers.Schedulers;
import utils.ActivityUtil;
import utils.TimeUtil;

public class LogDetailActivity extends BaseActivity {
    @BindView(R.id.rv_log_detail)
    RecyclerView recyclerView;
    @BindView(R.id.fl_log_detail_empty)
    FrameLayout flEmpty;
    @BindView(R.id.iv_log_detail_home)
    ImageView iv_Home;
    @BindView(R.id.iv_log_detail_return)
    ImageView iv_Return;
    @BindView(R.id.tv_log_detail_user)
    TextView tv_User;
    @BindView(R.id.tv_log_detail_role)
    TextView tv_Role;
    @BindView(R.id.tv_log_detail_departments)
    TextView tv_Departments;
    @BindView(R.id.tv_log_detail_cabinet)
    TextView tv_Cabinet;
    @BindView(R.id.tv_log_detail_operation)
    TextView tv_Operation;
    @BindView(R.id.tv_log_detail_number)
    TextView tv_Number;
    @BindView(R.id.tv_log_detail_time)
    TextView tv_Time;
    @BindView(R.id.tv_log_detail_sick_info)
    TextView tvLogDetailSickInfo;
    @BindView(R.id.tv_log_detail_Operation)
    TextView tvLogDetailOperation;
    @BindView(R.id.tv_log_detail_dept)
    TextView tvLogDetailDept;
    @BindView(R.id.tv_log_detail_hospital_number)
    TextView tvLogDetailHospitalNumber;
    @BindView(R.id.tv_log_detail_operation_time)
    TextView tvLogDetailOperationTime;
    @BindView(R.id.cd_log_detail_use)
    CardView cdLogDetailUse;

    private LogBean.LogDetailBean logDetailBean;
    private LogDetailAdapter adapter;
    private List<LogDetailBean> list = new ArrayList<>();
    private PopupWindow mPopupWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_log_detail);
        ButterKnife.bind(this);
    }

    @Override
    public void initView() {
        super.initView();
        Bundle bundle = getIntent().getBundleExtra(Constants.LOG_DETAIL);
        if (bundle != null) {
            logDetailBean = (LogBean.LogDetailBean) bundle.getSerializable(Constants.LOG_DETAIL_BUNDLE);
        }

        setdata();
        adapter = new LogDetailAdapter(LogDetailActivity.this, list);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(adapter);

        getLogDetails(String.valueOf(logDetailBean.getID()), logDetailBean.getOptionType());
    }

    @Override
    protected void setListener() {
        super.setListener();
//        adapter.setOnClickListener(new LogDetailAdapter.OnClickListener() {
//            @Override
//            public void onShowDetail(int position, TextView view, int xOffWidth) {
//                mPopupWindow = PopupWindowUtil.showPopupWindow(view, view.getText().toString(), xOffWidth, LogDetailActivity.this);
//            }
//        });

        adapter.setItemClickListener(new MyItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                LogDetailBean bean = list.get(position);

                String operate = logDetailBean.getOperate();
                if (operate.equals("出柜")){
                    operate = "取出";
                }else if (operate.equals("入柜")){
                    operate = "放入";
                }
                String status = operate;

                GoodsDetailInfoBean infoBean = new GoodsDetailInfoBean();
                infoBean.setName(bean.getGoodsName());
                infoBean.setBarCode(bean.getBarCodeList());
                infoBean.setSpecification(bean.getSpecification());
                infoBean.setSupplier(bean.getSupplier());
                infoBean.setUnit(bean.getUnit());
                infoBean.setNumber(Integer.parseInt(bean.getNumber()));
                infoBean.setType(2);
                infoBean.setTypeStatus(status);

                infoBean.setTitle("日志");
                infoBean.setTitleContent("日志详情");
                infoBean.setTitleThree("物品详情");

                Bundle bundle = new Bundle();
                bundle.putSerializable(Constants.GOODS_DETIAL_INFO,infoBean);
                Intent intent = new Intent(LogDetailActivity.this, GoodsDetialActivity.class);
                intent.putExtra("bundle", bundle);
                startActivity(intent);
            }
        });
    }

    private void setdata() {

        tv_User.setText(logDetailBean.getName());
        tv_Role.setText(logDetailBean.getRoleInfo());
        tv_Departments.setText(logDetailBean.getDepartment());
        tv_Cabinet.setText(logDetailBean.getLogicNumber() + "号柜");
        tv_Number.setText(logDetailBean.getCount() + "");
        tv_Time.setText(TimeUtil.getTime(logDetailBean.getSubTime()));
        String operate = logDetailBean.getOperate();
        if ("出柜".equals(operate)) {
            operate = "取出";
        } else if ("入柜".equals(operate)) {
            operate = "放入";
        }
        tv_Operation.setText(operate);

        if ("使用".equals(operate)){
            tvLogDetailSickInfo.setText(logDetailBean.getSickName()+ "/"+logDetailBean.getSickAge()+"/"+logDetailBean.getSickGender());
            tvLogDetailOperation.setText(logDetailBean.getOperatName());
            tvLogDetailDept.setText(logDetailBean.getPatientDept()+"/"+logDetailBean.getBedCode()+"床");
            tvLogDetailHospitalNumber.setText(logDetailBean.getResidenceCode());
            tvLogDetailOperationTime.setText(TimeUtil.getTime(logDetailBean.getOperatTime()));
        }else {
            cdLogDetailUse.setVisibility(View.GONE);
        }
    }

    private void getLogDetails(String logId, final int optionType) {
        showLoadingView(flEmpty);
        GetRetrofit.getInstance().getLogDetail(NetAddress.token, NetAddress.machineCode, logId).subscribeOn(Schedulers.io())
                .groupBy(new Func1<List<OperateLogDetailsBean>, Boolean>() {
                    @Override
                    public Boolean call(List<OperateLogDetailsBean> operateLogDetailsBeen) {
                        return operateLogDetailsBeen == null ? false : operateLogDetailsBeen.size() > 0;
                    }
                }).observeOn(AndroidSchedulers.mainThread()).flatMap(new Func1<GroupedObservable<Boolean, List<OperateLogDetailsBean>>, Observable<OperateLogDetailsBean>>() {
            @Override
            public Observable<OperateLogDetailsBean> call(GroupedObservable<Boolean, List<OperateLogDetailsBean>> booleanListGroupedObservable) {
                if (booleanListGroupedObservable.getKey()) {
                    return booleanListGroupedObservable.observeOn(Schedulers.io()).flatMap(new Func1<List<OperateLogDetailsBean>, Observable<OperateLogDetailsBean>>() {
                        @Override
                        public Observable<OperateLogDetailsBean> call(List<OperateLogDetailsBean> operateLogDetailsBeen) {
                            return Observable.from(operateLogDetailsBeen).doOnNext(new Action1<OperateLogDetailsBean>() {
                                @Override
                                public void call(OperateLogDetailsBean operateLogDetailsBean) {
                                    LogDetailBean logDetailBean = new LogDetailBean();
                                    logDetailBean.setGoodsName(operateLogDetailsBean.getGoodName());
                                     logDetailBean.setSpecification(operateLogDetailsBean.getSpecification());
                                    logDetailBean.setSupplier(operateLogDetailsBean.getManufacturer());
                                    logDetailBean.setNumber(String.valueOf(operateLogDetailsBean.getNumber()));
                                    logDetailBean.setUnit(operateLogDetailsBean.getGoodsUnit());
                                    logDetailBean.setBarCode(operateLogDetailsBean.getBarCode());
                                    logDetailBean.setStatus(operateLogDetailsBean.getStatus()+"");
                                    logDetailBean.setReturnTime(operateLogDetailsBean.getReturnTime());
                                    logDetailBean.setIntoCabinetTime(operateLogDetailsBean.getIntoCabinetTime());
                                    list.add(logDetailBean);
                                }
                            }).last();
                        }
                    });
                } else {
                    hideLoadingView();
                    showEmptyView(flEmpty);
                    return null;
                }
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<OperateLogDetailsBean>() {
            @Override
            public void call(OperateLogDetailsBean operateLogDetailsBean) {
                hideLoadingView();
                List<LogDetailBean> data = new ArrayList<>();
                Map<String, LogDetailBean> map = new HashMap();
                LogDetailBean logDetailBean;
                Log.e(TAG, "call: "+ list.size() );
                for (int i = 0; i < list.size(); i++) {
                    logDetailBean = list.get(i);
                    String key = logDetailBean.getGoodsName() + logDetailBean.getSpecification() + logDetailBean.getSupplier();
                    if (map.containsKey(key)) {
                        LogDetailBean bean = map.get(key);
                        logDetailBean.setNumber((Integer.parseInt(bean.getNumber()) + 1) + "");
                        logDetailBean.getBarCodeList().addAll(bean.getBarCodeList());
                    }

                    String time;
                    if (TextUtils.isEmpty(logDetailBean.getReturnTime())){
                        if (!TextUtils.isEmpty(logDetailBean.getIntoCabinetTime())) {
                            time = TimeUtil.getNowTime(logDetailBean.getIntoCabinetTime()).substring(0, 19);
                        }else {
                            time = TimeUtil.getMillisecondDate().substring(0,TimeUtil.getMillisecondDate().length() - 4);
                        }
                    }else {
                        time = TimeUtil.getNowTime(logDetailBean.getReturnTime()).substring(0,19);
                    }

                    logDetailBean.getBarCodeList().add(logDetailBean.getBarCode() + Constants.INCREASE_DECREASE_SPLIT + time);
                    map.put(key, logDetailBean);
                }
                Set set = map.entrySet();
                Iterator iterator = set.iterator();
                while (iterator.hasNext()) {
                    Map.Entry mapentry = (Map.Entry) iterator.next();
                    LogDetailBean bean1 = (LogDetailBean) mapentry.getValue();
                    data.add(bean1);
                }

                list.clear();
                list.addAll(data);

                for (int i = 0; i < list.size(); i++) {
                    LogDetailBean logDetailBean1 = list.get(i);
                    for (int i1 = 0; i1 < logDetailBean1.getBarCodeList().size(); i1++) {
                        Log.e(TAG, "call: " + logDetailBean1.getBarCodeList().get(i1) + logDetailBean1.getNumber() );
                    }
                    Log.e(TAG, "call: -------------------------------------" );
                }

                adapter.notifyDataSetChanged();
            }
        }, new MyAction1());

    }

    @OnClick({R.id.iv_log_detail_home, R.id.iv_log_detail_return})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_log_detail_home:
                ActivityUtil.jumpToActivity(LogDetailActivity.this, MainActivity.class);
                finish();
                break;
            case R.id.iv_log_detail_return:
                finish();
                break;
        }
    }

    @Override
    protected void onHandleMessage(Message msg) {
        super.onHandleMessage(msg);
        switch (msg.what) {
            case HandlerConstant.ACTION_UP:
                if (mPopupWindow != null) {
                    mPopupWindow.dismiss();
                }
                break;
        }
    }
}
